import React, { useEffect, useState } from "react";
import {Link} from "react-router-dom"
export default function Carousel() {
  //状态数据 - 广告列表
  let [adList, setAdList] = useState([]);
  //状态数据 当前广告序号
  let[curAd,setCurAd]=useState(0)
  //定时器
  //生命周期 - 组件挂载时，异步请求广告列表
  useEffect(function () {
    //TODO: 此处的广告列表应该从服务器端接口异步请求获得
    let adList = [
      { aid: 10, pic: "images/banner_01.jpg", href: "/product?pid=3" },
      { aid: 13, pic: "images/banner_02.jpg", href: "/product?pid=4" },
      { aid: 15, pic: "images/banner_03.jpg", href: "/product?pid=6" },
      { aid: 17, pic: "images/banner_04.jpg", href: "/product?pid=7" },
    ];
    setAdList(adList);
  }, []); 
  
  useEffect(
    function(){
    let timer=null;
    if(adList.length){
        timer=setInterval(function(){
        let i=curAd+1
        i=i>=adList.length ?0:i;
        setCurAd(i)
      },1000)
    }
    return function(){
        clearInterval(timer)
    };
  },
  [adList,curAd]
  );
  // 后退
  function prev(){
    let i=curAd-1
    i=i<0 ?adList.length-1:i
    console.log(i)
    setCurAd(i)
  }
  function next(){
    let i=curAd+1
    i=i>=4?0:i
    setCurAd(i)
  }


  return (
    <div className="banner">
      {/* 图片列表 */}
      <ul>
        {adList.map((ad,i)=>(
          <li   
          key={i} style={{background: `url(${ad.pic})center 0 no-repeat`,
            display:i===curAd?"block":'none',
            zIndex:i===curAd?20:10}}>
          <Link to={ad.href} className="link"></Link>

          </li>
        ))}
        {/* <li style="background: url(images/banner_01.jpg) center 0 no-repeat; display: block;z-index: 20;">
          <a href="#" className="link"></a>
        </li>
        <li style="background: url(images/banner_02.jpg) center 0 no-repeat;">
          <a href="#" className="link"></a>
        </li>
        <li style="background: url(images/banner_03.jpg) center 0 no-repeat;">
          <a href="#" className="link"></a>
        </li>
        <li style="background: url(images/banner_04.jpg) center 0 no-repeat;">
          <a href="#" className="link"></a>
        </li> */}
      </ul>
      {/* 左右箭头 */}
      <span className="cut prev"  onClick={prev}></span>
      <span className="cut next"  onClick={next}></span>
      {/* 小圆点指示器 */}
      <div className="indicator">
        {adList.map((ad,i)=>( 
         <a href="/#" key={i} className={i===curAd?"cur":undefined} onClick={()=>setCurAd(i)}></a>
        ))}
      </div>
    </div>
  );
}
